import { Game } from "phaser";
import Preloader from "./scenes/Preloader";
import Boot from "./scenes/Boot";
import Test from "./scenes/Test";
import Layout from "./scenes/Layout";
// import Login from "./scenes/Login";
// import RexUIPlugin from "phaser3-rex-plugins/templates/ui/ui-plugin";
import QGamePlugin from "phaser-qgame/dist/QGamePlugin";

// import { SpinePlugin } from "@esotericsoftware/spine-phaser";

// More information about config: https://newdocs.phaser.io/docs/3.70.0/Phaser.Types.Core.GameConfig
const config = {
    type: Phaser.AUTO,
    parent: "phaser-container",
    // width: 1920,
    // height: 1080,
    // width: 1280,
    // height: 720,
    backgroundColor: "#222222",
    // pixelArt: true,
    // roundPixel: false,
    antialias: true,
    max: {
        // width: 1920,
        // height: 1080,
        // width:960,
        // height:540,
        // width: 1280,
        // height: 720,
    },
    scale: {
        mode: Phaser.Scale.FIT,
        // autoCenter: Phaser.Scale.CENTER_BOTH,
        parent: "phaser-container",
        resolution: window.devicePixelRatio || 1,
        // width: "100%",
        // height: "100%",
        // width: 1024,
        // height: 768,
    },
    physics: {
        default: "matter",
        matter: {
            gravity: { y: 0, x: 0 },
            enableSleep: false,
            debug: false,
        },
    },
    // fps: {
    //     limit: 120,
    // },
    input: {
        activePointers: 2, // 启用多点触摸支持
    },
    // 这是加场景
    scene: [Boot, Preloader, Test, Layout],
    plugins: {
        scene: [
            // {
            //     key: "SpinePlugin",
            //     plugin: SpinePlugin,
            //     mapping: "spine",
            // },
            // {
            //     key: "RexUIPlugin",
            //     plugin: RexUIPlugin,
            //     mapping: "rexUI",
            // },
            {
                key: "QGamePlugin",
                plugin: QGamePlugin,
                mapping: "qGame",
            },
        ],
    },
};

window.game = new Game(config);

import { Mask_Show, Mask_AddCloseFunction } from "/component/Mask.js";

import { POPMenuObject, POPMenuClose } from "../component/POPMenu.js";
import { Tools_Init } from "../component/ToolsMenu.js";
import SlowReminder from "../component/SlowReminder.js";
import {
    ProjectInit,
    ProjectSave,
    ProjectGetImageFiles,
    ProjectUpdateList,
    ProjectExportPackage,
} from "../component/ProjectMange.js";
import { Login_Init, Login_BoxCancel } from "../component/login.js";
import { FileInit } from "../component/FileMange.js";

window.UISetingImageSelector = function () {
    // <!-- <input class="attribute-value" style="border: none; outline: none;" type="url" /> -->
    const imageSelect = document.getElementById("imageSelect");
    if (imageSelect === null) return;
    // imageSelect.childNodes
    imageSelect.innerHTML = '<option value="" selected="true"></option>';

    // console.log('')

    const images = ProjectGetImageFiles();
    images.forEach((image) => {
        const option = document.createElement("option");
        option.value = image.relative;
        option.textContent = image.name;
        imageSelect.appendChild(option);
    });
};

// function PhaserLoadImageList(imageList, callback = null) {
//     window["layout"].loadImage(imageList, callback);
// }

window.placeComponents = function (type) {
    console.log(type);
    switch (type) {
        case "view":
            window["layout"].addView();
            break;
        case "label":
            window["layout"].addLabel();
            break;
        case "vertical":
            window["layout"].addVertical();
            break;
        case "horizontal":
            window["layout"].addHertical();
            break;
        case "grid":
            window["layout"].addGrid();
            break;
        case "scroll":
            window["layout"].addScroll();
            break;
        case "button":
            window["layout"].addButton();
            break;
        case "input":
            window["layout"].addInput();
            break;
    }
};

const tbody = document.getElementById("tree-tbody");

/** 根据组件名称显示不同的属性编辑项 */
function showAttributeBox(compleName) {
    document.getElementById("attr_alignX").style.display = "none";
    document.getElementById("attr_paddingLeft").style.display = "none";
    document.getElementById("attr_paddingRight").style.display = "none";
    document.getElementById("attr_paddingTop").style.display = "none";
    document.getElementById("attr_paddingBottom").style.display = "none";
    document.getElementById("attr_alignY").style.display = "none";
    document.getElementById("image-attribute").style.display = "none";
    document.getElementById("label-attribute").style.display = "none";
    document.getElementById("attr_placeholder").style.display = "none";
    document.getElementById("layout-attribute").style.display = "none";

    switch (compleName) {
        case "QUIVerticalLayout":
        case "QUIHorizontalLayout":
        case "QUIGridLayout":
            document.getElementById("layout-attribute").style.display =
                "inline-block";
            if (compleName === "QUIVerticalLayout") {
                document.getElementById("attr_paddingTop").style.display =
                    "inline-block";
                document.getElementById("attr_paddingBottom").style.display =
                    "inline-block";
                document.getElementById("attr_alignY").style.display =
                    "inline-block";
            } else if (compleName === "QUIHorizontalLayout") {
                document.getElementById("attr_paddingLeft").style.display =
                    "inline-block";
                document.getElementById("attr_paddingRight").style.display =
                    "inline-block";
                document.getElementById("attr_alignX").style.display =
                    "inline-block";
            } else if (compleName === "QUIGridLayout") {
                document.getElementById("attr_alignX").style.display =
                    "inline-block";
                document.getElementById("attr_alignY").style.display =
                    "inline-block";
                document.getElementById("attr_paddingLeft").style.display =
                    "inline-block";
                document.getElementById("attr_paddingRight").style.display =
                    "inline-block";
                document.getElementById("attr_paddingTop").style.display =
                    "inline-block";
                document.getElementById("attr_paddingBottom").style.display =
                    "inline-block";
            }

            break;
        case "QUIView":
            document.getElementById("image-attribute").style.display =
                "inline-block";
            break;
        case "QUIButton":
            document.getElementById("label-attribute").style.display =
                "inline-block";
            break;
        case "QUIInput":
            document.getElementById("attr_placeholder").style.display =
                "inline-block";
            document.getElementById("label-attribute").style.display =
                "inline-block";
            break;
        case "QUILabel":
            document.getElementById("label-attribute").style.display =
                "inline-block";
            break;

        default:
            // document.getElementById("layout-attribute").style.display = "none";
            break;
    }
}

function nodeTreeHtml(nodes, depth = 1) {
    if (nodes == null) return "";
    let html = "";
    for (let i = 0; i < nodes.length; i++) {
        const node = nodes[i];

        let paddingLeft = 20 * depth;
        html +=
            `
            <tr class="tree-item"  depth="${depth}" uuid="` +
            node["uuid"] +
            `">
                <td>
                    <div style="padding-left:` +
            paddingLeft +
            `px;">
                        <span class="tree-content">` +
            node["id"] +
            `</span>
                    </div>
                </td>
                <td>` +
            node["name"] +
            `</td>
            </tr>`;
        if (node.childViews.length > 0) {
            html += nodeTreeHtml(node.childViews, depth + 1);
        }
    }
    return html;
}

window.renderingTree = function (node) {
    if (node == null) {
        return;
    }
    if (tbody === null) return;
    // console.log(node);
    const nodeHtml =
        //  onclick="window.onTreeItemClick(this)"
        `
        <tr class="tree-item tree-item-select" depth="0" uuid="` +
        node["uuid"] +
        `">

            <td>
                <div>
                    <span class="tree-content">` +
        node["id"] +
        `</span>
                </div>
            </td>
            <td>` +
        node["name"] +
        `</td>
        </tr>`;
    let htmltext = nodeHtml;

    if (node.childViews.length > 0) {
        htmltext += nodeTreeHtml(node.childViews, 1);
    }
    tbody.innerHTML = htmltext;
};

let moveTreeItem = null;
let timeHandler = null;
let isMouseDown = false;
// 鼠标按下事件
tbody.addEventListener("mousedown", function (event) {
    // console.log(event.target.parentElement);
    const element = event.target.parentElement;
    if (element == null) return;

    let uuid = element.getAttribute("uuid");
    if (uuid == undefined) {
        return;
    }
    let items = document.getElementsByClassName("tree-item");
    for (let i = 0; i < items.length; i++) {
        items[i].className = items[i].className
            .split(" ")
            .filter((cls) => cls !== "tree-item-select")
            .join(" ");
    }
    element.className += " tree-item-select";
    window["layout"].selectd(uuid);

});

let moveOffset = 0;
// 鼠标松开事件
window.addEventListener("mouseup", function (event) {
    // console.log(event);
    if (moveTreeItem) {
        if (isMouseDown == true && moveOffset != 0) {
            window["layout"].move(moveOffset);
        }
        moveTreeItem.style.backgroundColor = "";
        clearTimeout(timeHandler);
        moveTreeItem = null;
        isMouseDown = false;
        moveOffset = 0;
    }
});

// 鼠标移动事件
tbody.addEventListener("mousemove", function (event) {

});


window.selectd = function (uuid) {
    let items = document.getElementsByClassName("tree-item");

    for (let i = 0; i < items.length; i++) {
        items[i].className = items[i].className
            .split(" ")
            .filter((cls) => cls !== "tree-item-select")
            .join(" ");
        const current_uuid = items[i].getAttribute("uuid");
        if (uuid == current_uuid) {
            items[i].className += " tree-item-select";
        }
    }
};

const attr = document.getElementsByClassName("attribute-item");

for (let i = 0; i < attr.length; i++) {
    const element = attr[i];
    const attributeName = element.getAttribute("id");
    const attrName = attributeName.split("_")[1];
    let valueEle = element.getElementsByClassName("attribute-value")[0];
    valueEle.addEventListener("input", function () {
        let value = "";
        if (valueEle.tagName === "INPUT") {
            // valueEle.value = valueEle.value.replace(/[^0-9]/g, '');
            value = valueEle.value;
        } else if (valueEle.tagName === "SELECT") {
            value = valueEle.value;
            console.log(attrName, value);
        } else {
            if (attrName === "id" || attrName === "class") {
                valueEle.innerText = valueEle.innerText.replace(
                    /[^0-9|a-z|A-Z|_]/g,
                    ""
                );
            }
            // else if(attrName === 'width' || attrName === 'height'){
            //     valueEle.innerText = valueEle.innerText.replace(/[^0-9|%]/g, '');
            // }
            else {
                if (attrName != "text" && attrName != "placeholder") {
                    valueEle.innerText = valueEle.innerText.replace(
                        /[^0-9]/g,
                        ""
                    );
                }
            }

            const range = document.createRange();
            range.selectNodeContents(valueEle);
            range.collapse(false);
            const selection = window.getSelection();
            selection.removeAllRanges();
            selection.addRange(range);
            value = valueEle.innerText;
        }

        // if(attrName === 'width' || attrName === 'height'){
        // window['layout'].setAttribute(attrName, value);
        // }else{
        window["layout"].setAttribute(attrName, value);
        // }
    });

    valueEle.addEventListener("contextmenu", function (e) {
        console.log("右键菜单");
        e.preventDefault();

        const name = element.querySelector(".attribute-name").innerHTML;
        // const rect = valueEle.getBoundingClientRect();
        // const menu = new POPMenuObject({ x: rect.left, y: rect.top });

        console.log(e.target);
        if (e.target.getAttribute("type") === "range") {
            let result = prompt(name, e.target.value);
            if (result) {
                e.target.value = result;
                e.target.dispatchEvent(new Event("input"));
            }
        }
    });

    valueEle.addEventListener("keydown", (event) => {
        if (event.key === "Enter") {
            event.preventDefault();
            valueEle.blur();
        }
    });
}

/* 批量设置属性值 */
function batchSetAttributeValue(attributes) {
    // const attr = document.getElementsByClassName('attribute-item');
    for (let i = 0; i < attr.length; i++) {
        const element = attr[i];
        const attributeName = element.getAttribute("id");
        const attrName = attributeName.split("_")[1];
        if (attrName === "background" || attrName === "borderColor") {
            // 转RRGGBB格式
            if (attributes[attrName] === undefined) {
                attributes[attrName] = 0;
            } else {
                attributes[attrName] = parseInt(attributes[attrName]).toString(
                    16
                );
                while (attributes[attrName].length < 6) {
                    attributes[attrName] = "0" + attributes[attrName];
                }
                attributes[attrName] = "#" + attributes[attrName].toString(16);
            }
        }
        // if( attrName === "fontColor"){
        //     attributes[attrName] = "#" + attributes[attrName].toString(16);
        // }
        let valueEle = element.getElementsByClassName("attribute-value")[0];
        if (attributes[attrName] === undefined) {
            if (valueEle.tagName === "INPUT") {
                if (valueEle.type === "color") {
                    valueEle.value = "#000000";
                } else if (valueEle.type === "range") {
                    valueEle.value = 0;
                } else {
                    valueEle.value = "-";
                }
            } else {
                valueEle.innerText = "-";
            }
        } else {
            if (valueEle.tagName === "INPUT") {
                switch (attrName) {
                    case "alpha":
                        valueEle.value = attributes[attrName] * 100;
                        break;
                    default:
                        valueEle.value = attributes[attrName];
                }
            } else if (valueEle.tagName === "SELECT") {
                valueEle.value = attributes[attrName];
            } else {
                valueEle.innerText = attributes[attrName];
            }
        }
    }
}

const attributeBox = document.getElementById("attribute-box");
window.onDeleteComponent = function () {
    if (attributeBox) {
        attributeBox.style.display = "none";
    }
};

window.onCancelSelectComponent = function () {
    if (attributeBox) {
        attributeBox.style.display = "none";
    }
};

window.onSelectComponent = function (attribute, componentName) {
    if (attributeBox) {
        attributeBox.style.display = "inline-block";
    }
    showAttributeBox(componentName);
    batchSetAttributeValue(attribute);
};

window.loadXML = function (xml) {
    window["layout"].loadXML(xml);
};

window.addEventListener("contextmenu", function (e) {
    e.preventDefault();
});

Mask_AddCloseFunction(Login_BoxCancel);
Mask_AddCloseFunction(POPMenuClose);

ProjectInit();
Mask_Show();
Tools_Init();
Login_Init(() => {
    ProjectUpdateList();
});
FileInit();

// 快捷键
document.addEventListener("keydown", function (e) {
    // 快捷键存在优先级问题，多键组合必须放到前面
    // 3键组合
    // console.log(e);

    if (
        e.target.className == "attribute-value" ||
        e.target.className == "attribute-name"
    ) {
        return;
    }

    if (e.ctrlKey && e.altKey && e.key === "e") {
        ProjectExportPackage();
        SlowReminder("导出组件 CTRL+ALT+E");
    } else if (e.ctrlKey && e.altKey && e.key === "i") {
        ProjectImportPackage();
        SlowReminder("导入组件 CTRL+ALT+I");
    }
    // 2键组合
    else if (e.ctrlKey && e.key === "s") {
        e.preventDefault();
        ProjectSave();
        SlowReminder("保存 CTRL+S");
    } else if (e.ctrlKey && e.key === "z") {
        e.preventDefault();
        ProjectRevoke();
        SlowReminder("撤销 CTRL+Z");
    } else if (e.ctrlKey && e.key === "y") {
        e.preventDefault();
        ProjectRedo();
        SlowReminder("回撤 CTRL+Y");
    } else if (e.altKey && e.key === "f") {
        e.preventDefault();
        document.getElementById("tools_item_alt_f").click();
        SlowReminder("工具栏 文件 ALT+F");
    } else if (e.altKey && e.key === "e") {
        e.preventDefault();
        document.getElementById("tools_item_alt_e").click();
        SlowReminder("工具栏 编辑 ALT+E");
    } else if (e.altKey && e.key === "p") {
        e.preventDefault();
        document.getElementById("tools_item_alt_p").click();
        SlowReminder("工具栏 打包 ALT+P");
    } else if (e.ctrlKey && e.key === "x") {
        e.preventDefault();
        window["layout"].cut();
        SlowReminder("剪切 CTRL+X");
    } else if (e.ctrlKey && e.key === "c") {
        e.preventDefault();
        window["layout"].copy();
        SlowReminder("复制 CTRL+C");
    } else if (e.ctrlKey && e.key === "v") {
        e.preventDefault();
        window["layout"].paste();
        SlowReminder("粘贴 CTRL+V");
    }
    // 1键
    else if (e.key === "Escape") {
        // ToolsMenuCancel();
    } else if (e.key === "Delete") {
        e.preventDefault();
        window["layout"].delete();
        SlowReminder("删除节点 Delete");
    }
    window["layout"].keydown(e);
});
